<?php

namespace App\Modules\Rebate\Jobs;

use App\Modules\Good\Models\GoodSpec;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\Rebate\Models\RebateRule;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\Member;
use App\Modules\User\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RebateJob implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->handle();//队列方法，正式上线需要注释掉
    }

    public function handle()
    {
        if (empty($this->order->referrer_id)) {
            return null;
        }

        // 如果使用混合支付，不参与返利
        // 2021.11.1   Ezreal
        if ($this->order->is_balance == 1) {
            return null;
        }

        if ($this->order->type == Order::TYPE_PACKAGE) {
            return $this->packageRebate();
        } elseif ($this->order->type == Order::TYPE_GOOD) {
            return $this->goodRebate();
        }
    }

    public function packageRebate()
    {
        $rule = RebateRule::query()
            ->where('type', RebateRule::TYPE_PACKAGE)
            ->where('link_id', $this->order->link_id)
            ->first();
        if (is_null($rule)) {
            return null;
        }
        $money = 0;
        switch ($this->order->referrer_level) {
            case 1:
                // 返利会员奖励金额
                $member = Member::query()
                    ->where('user_id', $this->order->referrer_id)
                    ->where('shop_id', $this->order->shop_id)
                    ->first();
                if (!is_null($member)) {
                    $money = max(0, min($member->quota - $member->rebate, $rule->level1_rebate));
                    $member->increment('rebate', $money);
                }
                break;
            case 2:
                // 城市合伙人奖励金额
                $money = $rule->level2_rebate;
                break;
            case 3:
                $shop_id     = $this->order->shop_id;//商品所属门店id
                $referrer_id = $this->order->referrer_id;//推荐人id

                // 获取推荐人所属门店的所在集团id
                $shopIds = DB::table('users')->where('id', $referrer_id)->first('shop_id');
                $aUserInGroupId = DB::table('shops')->where('group_id', '!=', 0)->whereIn('id', json_decode($shopIds->shop_id))->get()->pluck('group_id')->all();
                $aUserInGroupId = array_unique($aUserInGroupId);
                    
                // 获取商品id所在门店的所在集团id
                $shop_info = DB::table('shops')->where('id', $shop_id)->first();
                $shop_group_id = $shop_info->group_id;

                if (!in_array($shop_group_id, $aUserInGroupId)) {
                    // 非本集团或商家职员奖励金额
                    $money = $rule->level4_rebate;
                }else{
                    // 本集团或商家职员奖励金额
                    $money = $rule->level3_rebate;
                }

                break;
        }

        /**
         *  临洮：    产生待审核金额的提醒
         *  模板ID：G8Sdfmz2b9HoPyrtaKr51gnxeOQSuiFa8f77h9om1sM
         *  格式：
         * {{first.DATA}}
         * 被推荐人：{{keyword1.DATA}}
         * 消费商家：{{keyword2.DATA}}
         * 消费金额：{{keyword3.DATA}}
         * 消费时间：{{keyword4.DATA}}
         * 推荐奖励：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        $user = User::query()->where("id", $this->order->user_id)->first();
        $referrer = User::query()->find($this->order->referrer_id);
        $shop = Shop::query()->find($this->order->shop_id);
        $template = DB::table("templates")->find(34);
        $first = vsprintf(json_decode($template->json, true)['first'], array($user->name));

        // Log::channel('pay')->info("消费金额：", $this->order->original_price);
        // Log::channel('pay')->info("money：", $money);
        // Log::channel('pay')->info("rule->level_2_3_rebate：", $rule->level_2_3_rebate);

        $sendData = [
            0 => $referrer->openid,
            1 => $user->name,
            2 => $shop->name,
            3 => ($this->order->original_price / 100) . "元",
            4 => date("Y年m月d日 H时i分s秒", strtotime($this->order->created_at)),
            5 => "",
            "first" => $first
        ];
        if ($money > 0) {
            Rebate::query()
                ->create([
                    'shop_id' => $this->order->shop_id,
                    'user_id' => $this->order->referrer_id,
                    'title' => $this->order->title,
                    'origin' => Order::class,
                    'link_id' => $this->order->id,
                    'buyer_id' => $this->order->user_id,
                    'price' => $this->order->original_price,
                    'money' => $money,
                    'status' => Rebate::STATUS_INIT,
                    'level' => $this->order->referrer_level,
                ]);
            $sendData[5] =($money / 100) . "元";
            sendMessage(34, $sendData);

        }
        if (!empty($this->order->personal_id) && $rule->level_2_3_rebate > 0) {
            Rebate::query()
                ->create([
                    'shop_id' => $this->order->shop_id,
                    'user_id' => $this->order->personal_id,
                    'title' => $this->order->title,
                    'origin' => Order::class,
                    'link_id' => $this->order->id,
                    'buyer_id' => $this->order->user_id,
                    'price' => $this->order->original_price,
                    'money' => $rule->level_2_3_rebate,
                    'status' => Rebate::STATUS_INIT,
                    'level' => 3,
                ]);
            $personal = User::query()->find($this->order->personal_id);
            if($personal){
                $sendData[0] =  $personal->openid;
                $sendData[5] = ($rule->level_2_3_rebate / 100) . "元";
                sendMessage(34, $sendData);
            }
            // $sendData[5] = ($rule->level_2_3_rebate / 100) . "元";
            // sendMessage(34, $sendData);
        }
        Log::channel('pay')->info("推荐订单数据：", $sendData);

    }

    public function goodRebate()
    {
        $detail = $this->order->detail;
        $specIds = array_column($detail, 'id');
        $rules = GoodSpec::query()
            ->whereIn('id', $specIds)
            ->get()
            ->keyBy('id');

        $member = Member::query()
            ->where('user_id', $this->order->referrer_id)
            ->where('shop_id', $this->order->shop_id)
            ->first();

        /**
         *  临洮：    产生待审核金额的提醒
         *  模板ID：G8Sdfmz2b9HoPyrtaKr51gnxeOQSuiFa8f77h9om1sM
         *  格式：
         * {{first.DATA}}
         * 被推荐人：{{keyword1.DATA}}
         * 消费商家：{{keyword2.DATA}}
         * 消费金额：{{keyword3.DATA}}
         * 消费时间：{{keyword4.DATA}}
         * 推荐奖励：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        $user = User::query()->where("id", $this->order->user_id)->first();
        $referrer = User::query()->find($this->order->referrer_id);
        $shop = Shop::query()->find($this->order->shop_id);
        $template = DB::table("templates")->find(34);
        $first = vsprintf(json_decode($template->json, true)['first'], array($user->name));
        // Log::channel('pay')->info("消费金额：", $this->order->original_price);
        // Log::channel('pay')->info("money：", $money);
        // Log::channel('pay')->info("rule->level_2_3_rebate：", $rule->level_2_3_rebate);
        $sendData = [
            0 => $referrer->openid,
            1 => $user->name,
            2 => $shop->name,
            3 => ($this->order->original_price / 100) . "元",
            4 => date("Y年m月d日 H时i分s秒", strtotime($this->order->created_at)),
            5 => "",
            "first" => $first
        ];
        foreach ($detail as $item) {
//            $member = $members->get($this->order->shop_id);
            $rule = $rules->get($item['id']);
            if (is_null($rule)) {
                continue;
            }
            $money = 0;
            switch ($this->order->referrer_level) {
                case 1:
                    // 返利会员奖励金额
                    if (!is_null($member)) {
                        $money = max(0, min($member->quota - $member->rebate, $rule->level1_rebate));
                        $member->increment('rebate', $money);
                    }
                    break;
                case 2:
                    // 城市合伙人奖励金额
                    $money = $rule->level2_rebate;
                    break;
                case 3:
                    $shop_id     = $this->order->shop_id;//商品所属门店id
                    $referrer_id = $this->order->referrer_id;//推荐人id

                    // 获取推荐人所属门店的所在集团id
                    $shopIds = DB::table('users')->where('id', $referrer_id)->first('shop_id');
                    $aUserInGroupId = DB::table('shops')->where('group_id', '!=', 0)->whereIn('id', json_decode($shopIds->shop_id))->get()->pluck('group_id')->all();
                    $aUserInGroupId = array_unique($aUserInGroupId);
                        
                    // 获取商品id所在门店的所在集团id
                    $shop_info = DB::table('shops')->where('id', $shop_id)->first();
                    $shop_group_id = $shop_info->group_id;

                    if (!in_array($shop_group_id, $aUserInGroupId)) {
                        // 非本集团或商家职员奖励金额
                        $money = $rule->level4_rebate;
                    }else{
                        // 本集团或商家职员奖励金额
                        $money = $rule->level3_rebate;
                    }
                    // $money = $rule->level3_rebate;
                    break;
            }
            if ($money > 0) {
                Rebate::query()
                    ->create([
                        'shop_id' => $item['shop_id'],
                        'user_id' => $this->order->referrer_id,
                        'title' => $item['good_name'],
                        'origin' => Order::class,
                        'link_id' => $this->order->id,
                        'buyer_id' => $this->order->user_id,
                        'price' => $item['price'] * $item['number'],
                        'money' => $money * $item['number'],
                        'status' => Rebate::STATUS_INIT,
                        'level' => $this->order->referrer_level,
                    ]);
                $sendData[3] = (($item['price'] * $item['number']) / 100) . "元";
                $sendData[5] = (($money * $item['number']) / 100) . "元";
                sendMessage(34, $sendData);
            }
            if (!empty($this->order->personal_id) && $rule->level_2_3_rebate > 0) {
                Rebate::query()
                    ->create([
                        'shop_id' => $item['shop_id'],
                        'user_id' => $this->order->personal_id,
                        'title' => $item['good_name'],
                        'origin' => Order::class,
                        'link_id' => $this->order->id,
                        'buyer_id' => $this->order->user_id,
                        'price' => $item['price'] * $item['number'],
                        'money' => $rule->level_2_3_rebate * $item['number'],
                        'status' => Rebate::STATUS_INIT,
                        'level' => 3,
                    ]);
                $sendData[3] =  (($item['price'] * $item['number']) / 100) . "元";
                $sendData[5] =  (($rule->level_2_3_rebate * $item['number']) / 100) . "元";
                sendMessage(34, $sendData);
            }

            Log::channel('pay')->info("推荐订单数据：", $sendData);
        }
    }
}
